package com.lovo.commom.util;

import net.coobird.thumbnailator.Thumbnails;


import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;


public class ImageysUtils {
    /**
     * 压缩base64编码至500以内
     *
     * @param base64Img
     * @return
     */
    public static String resizeImageTo500K(String base64Img) {
        try {
            if (base64Img.contains("data:")){
                int start=base64Img.indexOf(",");
                base64Img=base64Img.substring(start+1);
            }
            base64Img=base64Img.replaceAll("\r\n","").trim();
            byte[] bytes1 = java.util.Base64.getDecoder().decode(base64Img);
            InputStream stream = new ByteArrayInputStream(bytes1);
            BufferedImage src = ImageIO.read(stream);
            BufferedImage output = Thumbnails.of(src).size(src.getWidth() / 3, src.getHeight() / 3).asBufferedImage();
//            BufferedImage output = Thumbnails.of(src).size(1000, 600).asBufferedImage();
            String base64 = imageToBase64(output);
            while (base64.length() - base64.length() / 8 * 2 > 50000) {
                output = Thumbnails.of(output).scale(0.5).asBufferedImage();
                base64 = imageToBase64(output);
            }
            return base64;
        } catch (Exception e) {
            e.printStackTrace();
            return base64Img;
        }
    }

//    /**
//     * BufferedImage转换成base64，在这里需要设置图片格式,因为我需要jpg格式就设置了jpg
//     */
//    public static String imageToBase64(BufferedImage bufferedImage) {
//        Base64 encoder = new Base64();
//        ByteArrayOutputStream baos = new ByteArrayOutputStream();
//        try {
//            ImageIO.write(bufferedImage, "jpg", baos);
//        } catch (IOException e) {
//        }
//        return new String(encoder.encode((baos.toByteArray())));
//    }
    /**
     * BufferedImage转换成base64，在这里需要设置图片格式,因为我需要jpg格式就设置了jpg
     */
    public static String imageToBase64(BufferedImage bufferedImage) {

        ByteArrayOutputStream baos = new ByteArrayOutputStream();//io流
        try {
            ImageIO.write(bufferedImage, "png", baos);//写入流中
        } catch (IOException e) {
            e.printStackTrace();
        }
        byte[] bytes = baos.toByteArray();//转换成字节
        String jpg_base64 = java.util.Base64.getEncoder().encodeToString(bytes);
        jpg_base64 = jpg_base64.replaceAll("\n", "").replaceAll("\r", "");//删除 \r\n
        return "data:image/jpg;base64," + jpg_base64;
    }

}